package com.gy.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.User;
import com.gy.entity.result.CopyRight;
import com.gy.entity.result.Papers;
import com.gy.mapper.CopyRightMapper;
import com.gy.query.CopyRightQuery;
import com.gy.query.PapersQuery;
import com.gy.result.Result;
import com.gy.service.CopyRightService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CopyRightServiceImpl extends ServiceImpl<CopyRightMapper, CopyRight> implements CopyRightService {
    @Autowired
    private UploadController uploadController;

    @Autowired
    private CopyRightMapper copyRightMapper;

    @Autowired
    private UserService userService;
    @Override
    public Result<PageVO<CopyRight>> getPapers(CopyRightQuery copyRightQuery) {
        Long openId = UserHolder.getUser().getUserId();
        if (openId == null) {
            return Result.error("用户登录信息异常");
        }
        Page<CopyRight> page = Page.of(copyRightQuery.getPageNo(), copyRightQuery.getPageSize());
        // 排序条件
        if (!copyRightQuery.getSortBy().isEmpty() || copyRightQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(copyRightQuery.getSortBy(), copyRightQuery.getIsAsc()));
        } else {
            // 为空，默认按照出版时间排序
            page.addOrder(new OrderItem("id", false));
        }
        // 构建查询条件
        LambdaQueryChainWrapper<CopyRight> queryWrapper = lambdaQuery().select()
                .eq(openId != null, CopyRight::getUserId, openId);

        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (copyRightQuery.getStartDate() != null && copyRightQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(copyRightQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(copyRightQuery.getEndDate());
                queryWrapper.between(CopyRight::getPuttime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        //添加个人排名参数查询
        if (copyRightQuery.getAuthorRank() != null) {
            queryWrapper.eq(CopyRight::getAuthorRank, copyRightQuery.getAuthorRank());
        }
        Page<CopyRight> copyRightPage = queryWrapper.page(page);

        //封装VO结果
        PageVO<CopyRight> vo = new PageVO<>();
        vo.setTotal(copyRightPage.getTotal());
        vo.setPages(copyRightPage.getPages());
        List<CopyRight> records = copyRightPage.getRecords();
        if (records.isEmpty()) {
            vo.setList(Collections.emptyList());
        } else {
            //拷贝
            vo.setList(records);
        }
        return Result.success(vo);

    }
    @Override
    @Transactional
    public Result removeCopyRight(Long id) {
        CopyRight copyRight = getById(id);
        if (copyRight == null) {
            return Result.error("版权信息未找到");
        }

        String pdfPath = copyRight.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除版权信息失败");
        }
        userService.decrementUserCopyrightCount();


        return Result.success("版权信息删除成功");
    }


    /**
     * 根据id主键查看软件著作权
     * @param id
     * @return
     */
    @Override
    public CopyRight getCopyRightById(Long id) {
        if (id == null) {
            return null;
        }
        return  copyRightMapper.selectCopyrightById(id);

    }

    @Override
    public Result updateCopyRight(CopyRight copyRight) {
        // 参数验证
        if (copyRight == null) {
            return Result.error("版权信息不能为空");
        }
        if (copyRight.getId() == null) {
            return Result.error("版权ID不能为空");
        }

        try {
            int affectedRows = copyRightMapper.updateCopyright(copyRight);
            if (affectedRows > 0) {
                return Result.success(copyRight);
            } else {
                return Result.error("未找到对应的版权信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新版权信息时发生异常", e);
            return Result.error("更新版权信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveCopyRight(CopyRight copyRight) {
        if (copyRight == null) {
            log.warn("传入的版权对象为空");
            return Result.error("版权对象不能为空");
        }
        try {
            // 设置用户 ID
            copyRight.setUserId(UserHolder.getUser().getUserId());

            boolean save = copyRightMapper.saveCopyright(copyRight);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserCopyrightCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存版权时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getCopyRightByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<CopyRight> copyRightList = copyRightMapper.selectCopyrightBatchIds(Arrays.asList(ids));
            return Result.success(copyRightList);
        }
        return null;
    }


}
